#!/usr/bin/perl

use strict;
use warnings;
require 'forum_common.pl';

connect_to_database() or bad_deal();
my $user = get_current_user(get_sess_id());

record_this_hit();

print header($forum::http_header), forum_start(forum_cpanel($user));

my $id = url_param('id');
unless (defined $id)
{
	print forum_error('No board specified!');
	goto gameover;
}


my ($board, $num_pages, $page, $first, $last, $topics);
unless ($board = get_board($id))
{
	print forum_error();
	goto gameover;
}
my $board_title = escapeHTML($board->{TITLE});

$num_pages = ceil($board->{NUM_TOPICS}/$forum::t_p);
$page = defined($page = url_param('page')) ? int($page) : 0;
$page = $num_pages if ($page > $num_pages);
$page = 1 if ($page < 1);
$first = ($page-1)*$forum::t_p+1;
$last = ($page < $num_pages) ? $page*$forum::t_p : $board->{NUM_TOPICS};

unless ($topics = get_topics($board, $page))
{
	print forum_error();
	goto gameover;
}
#my $show_num_topics = $board->{NUM_TOPICS} ?
#					  "($first-$last of $board->{NUM_TOPICS})" :
#					  '0';
print	'Board: ', span({-class=>'title'}, $board_title), br(),
		br(),
		"Topics: ($first-$last)", br(),
		'Pages:';
for (1 .. $num_pages)
{
	print ' ', $_==$page ? $_ : a({-href=>"board.cgi?id=$id;page=$_"}, $_);
}
print	'<div id="topics">',
		div({-class=>'topic'},
			div({-class=>'topicc chief wide'}, 'Information'),
			div({-class=>'topicc chief'}, 'Posts'),
			div({-class=>'topicc chief dt'}, 'Last post was on'));
for my $topic (@$topics)
{
	my $title = escapeHTML($topic->{TITLE});
	my $descr = escapeHTML($topic->{DESCR}) || '&nbsp;';
	my $u_usernm = escapeHTML($topic->{U_USERNM});
	my $dt_started = timefmt($topic->{DT_STARTED});
	my $lp_dt_posted = timefmt($topic->{LP_DT_POSTED});
	print
		'<div class="topic">',
		div({-class=>'topicc'},
			div({-class=>'title'},
				a({-href=>"topic.cgi?id=$topic->{ID}",-class=>'strong'},
					$title)),
			div({-class=>'descr'}, $descr),
			div({-class=>'usernm'},
				'By:',
				a({-href=>"member.cgi?id=$topic->{STARTER}"}, $u_usernm)),
			div({-class=>'dt'}, "On: $dt_started")),
		div({-class=>'topicc nposts'}, $topic->{NUM_POSTS}),
		div({-class=>'topicc dt'}, $lp_dt_posted),
		'</div>';
}
if (!@$topics)
{
	print div({-style=>'padding:1em'},"No topics in <b>$board_title</b> yet");
}
print '</div><div id="topics_footer">';
if (my $reason = cant_maketopic($user, $board))
{
	print "[$reason]";
}
else
{
	print a({-href=>"newtopic.cgi?board=$id", -class=>'strong'}, 'New Topic');
}
print '</div>';


gameover:
print forum_end();
forum_disconnect();
